package com.javaweb.servlet;


import com.javaweb.common.DBUtil;
import com.javaweb.common.DispatcherTool;
import com.javaweb.common.StringTool;
import com.javaweb.entity.User;
import com.javaweb.filter.FilterFreeLogin;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * LoginServlet for login request.
 * there are two ways for configuring servlet
 *  A. in web.xml
 *  B. @WebServlet
 */

@WebServlet(name="loginServlet",
            urlPatterns = {"/loginServlet"}
)
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp) ;
    }
    /**
     * override doPost logic from father by our own business logic
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /**
         * process the arrived request in following logic.
         * At FIRST: SETTING ENCODING.
         */
        System.out.println("[INFO] entered login servlet.") ;
        /*
        step1: got parameters
         */
        String name = req.getParameter("name") ;
        String pwd = req.getParameter("pwd") ;
        String free = req.getParameter("free") ;
        // check the Nullable for the parameters
        if (StringTool.isEmpty(name, pwd)) {
            System.out.println("[INFO] LoginServlet: parameter was null .") ;
            DispatcherTool.indirectForwardToClient(req, resp, "01/servlet/login.jsp", "参数为空！" );
            return ;
        }
        // step 2: do computing by DB or 3rd API
        // validate the login  user
        User user = DBUtil.userLogin(name, pwd) ;
        if (user  == null) {
            DispatcherTool.indirectForwardToClient(req, resp, "01/servlet/login.jsp", "密码错误！" );
            return ;
        }
        /**
         * process the freelogin
         */
        if (! StringTool.isEmpty(free)) {
            String encryUserInfor = StringTool.encrypt(user.getName() , pwd) ;
            Cookie freeCookie = new Cookie(FilterFreeLogin.FREE_COOKIE, encryUserInfor) ;
            freeCookie.setMaxAge(2 * 60);
            resp.addCookie(freeCookie);
            System.out.println("[INFO] loginServlet a freeCookie was added!") ;
        }

        // validated user and cached the user in session
        System.out.println("[INFO] LoginServlet: User was validated.") ;
        HttpSession session = req.getSession() ;
        session.setAttribute("user", user);
        // step 3. return the response
        DispatcherTool.indirectForwardToClient(req, resp, "01/servlet/welcome.jsp", "登录成功！");
    }



}
